import { Injectable, Injector } from "@angular/core";
import { RequestOptionsArgs, Response, Headers } from "@angular/http";
import { Interceptor } from "./interceptor";
import { InterceptedRequest } from "./intercepted-request";
import { InterceptedResponse } from "./intercepted-response";
// import { ApplicationService } from "../application.service";
import { AppConfig } from "../../config";
/**
 * 请求拦截器
 *
 * @export
 * @class RequestInterceptor
 * @implements {IHttpInterceptor}
 */
@Injectable()
export class RequestInterceptor implements Interceptor {
  // authService: AuthenticationService;
  skipAuth: [string];

  constructor(
    private inject: Injector,
    // private applicationService: ApplicationService
  ) {
    // 用户登录或认证请求则不需要添加头部AccessToken信息
    this.skipAuth = [
      `${AppConfig.APP_RESTFUL}/webapi/v1/auth/login`,
    ];
  }

  public interceptBefore(request: InterceptedRequest): InterceptedRequest {
    //  this.applicationService = this.inject.get(ApplicationService); // 注意此句
    const req_started = Date.now();
		/**
		 * 如果是跳过认证的链接，则不添加头部信息
		 */
    if (this.isSkipAuth(request.url)) {
      request.options.headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': '',
      });
    } else {
      const access_token = localStorage.getItem('userToken').replace(/\"/g, '');
      request.options.headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': access_token
      });
    }
    return request;

  }
  public interceptAfter(response: InterceptedResponse): InterceptedResponse {
    return response;
  }

  /*
	 *是否跳过添加头部认证
	*/
  isSkipAuth(url: string) {
    let isMatch = false;
    this.skipAuth.forEach((reg_url: string) => {
      if (!isMatch) {
        if (url.search(reg_url) >= 0) {
          isMatch = true;
        }
      }
    });
    return isMatch;
  }
}



// WEBPACK FOOTER //
// ./src/app/service/interceptor/request.interceptor.ts